package com.jiu.util;

import java.io.InputStreamReader;
import java.security.MessageDigest;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;


//http://appimg2.qq.com/card/mk/card_info_v3.js
public class JavaScriptUtils {
	public static void main(String[] args) throws Exception {
		ScriptEngine engine = JavaScriptUtils.getScriptEngine();
		System.out.println(engine.eval("md5('1')"));
		System.out.println(md5("1"));
	}
	public static ScriptEngine getScriptEngine() throws Exception{
		ScriptEngineManager sc = new ScriptEngineManager();
		ScriptEngine engine = sc.getEngineByName("JavaScript");
		engine.eval(new InputStreamReader(JavaScriptUtils.class.getResourceAsStream("md5.js")));
		engine.eval("function getThemeCardMap(){var json = \"{\";for(var i=0;i<theme_card_list.length;i++){json += theme_card_list[i][0]+\":{\";for(var j=0;j<theme_card_list[i].length;j++){json += \"'\"+j+\"':'\"+theme_card_list[i][j]+\"',\"}json += \"},\";}json = json.substring(0,json.length-1)+\"}\";return json;}");   
		engine.eval("function getGiftMap(){var json = \"{\";for(var i=0;i<gift_list.length;i++){json += gift_list[i][2]+\":{\";for(var j=0;j<gift_list[i].length;j++){json += \"'\"+j+\"':'\"+gift_list[i][j]+\"',\"}json += \"},\";}json = json.substring(0,json.length-1)+\"}\";return json;}");
		return engine;
	}
	public static String md5(String s){
		MessageDigest md5 = null;
		try {md5 = MessageDigest.getInstance("MD5");} catch (Exception e) {}
		md5.update(s.getBytes());
		byte[] domain = md5.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		// converting domain to String
		for (int i = 0; i < domain.length; i++) {
			if (Integer.toHexString(0xFF & domain[i]).length() == 1) {
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & domain[i]));
			} else
				md5StrBuff.append(Integer.toHexString(0xFF & domain[i]));
		}
		return md5StrBuff.toString();
	}
	
}
